import { Component, OnInit, Injector, Output, EventEmitter, Input } from '@angular/core';
import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../public/serve/hints/hints.service';
import { RemoveTableService } from '../../../public/serve/remove-table/remove-table.service';
import { InitService } from '../../../public/serve/init/init.service';
import { keyword } from '../../keyword.data';
import { appKeywordUrl } from '../../keyword.url';
import { BaseTreeComponent } from '../../../public/components/base-tree/base-tree.component';
import { HttpClient } from '@angular/common/http';
import { TreeNode } from '../../../public/common/api';
import {appSynonymUrl} from '../../../synonym/synonym.url';
declare var $:any;
@Component({
  selector: 'app-trial-table',
  templateUrl: './trial-table.component.html',
  styleUrls: ['./trial-table.component.css']
})

export class TrialTableComponent implements OnInit {

  @Input() tabCheckStatus: any;
  total: number = 0;
  naturalNum: number = 0;
  totalRecords: number;
  public totalItems: number;
  changeCheck: any = 1;

  keywordTabVal: Array<object>;
  themeTagListVal : Array<object>;

  isSelectAll: boolean = false;
  isChose: boolean = false;

  files: TreeNode[];
  cols: any[];
  public opensearch: boolean;
  right: any = {
    "keyword": {},
    "keywordTrial": {},
    "keywordUnreviewed": {}
  };

  constructor(
    private server: Service,
    public request: CudTableService,
    private tableListService: CudTableService,
    private hintsService: HintsService,
    private removeTableService: RemoveTableService,
    public initService: InitService,
    private http: HttpClient
  ) { 
    this.right = $.extend(this.right, server.getRight());
  }

  ngOnInit() { 
    this.themeSeventEmit = this.server.themeSeventEmit.subscribe((value: any) => {
      this.opensearch = value;
    });

    keyword.pagination.pageNo = 1;
    keyword.pagination.pageSize = 20;
    this._themeTagList();
  }

  //取消订阅
  public themeSeventEmit: any;
  ngOnDestroy() {
    if (this.themeSeventEmit) {
      this.themeSeventEmit.unsubscribe();
    }
  }

  /**
   * 查询主题词列表
   */
  _keyworkTabList() {
    let data = this._tableData();
    this.request.postRequest(this.server.baseUrl +appKeywordUrl.getThemeWordsList, data).then((res: any) => {
      if (res.result_code === '0000') {
        this.keywordTabVal = res.result;
        this.files = this._processTreeData(this.keywordTabVal, 'themeWordsId', 'parentid', 'name');
        this.totalRecords = res.length;
        this.total = res.length;
      } else {
        this.hintsService.messages(res.message, res.result_code);
      }
      this._cancelChecked();
      return;
    })
      .catch((err: any) => {
        this.hintsService.messages("error", "error");
        this._cancelChecked();
        return;
      });
  }

  /**
   * 点击图标显示子级的主题词
   * @param queryData 
   * @param node 
   */
  public getChildrenList(queryData, node) {
    this.request.postRequest(this.server.baseUrl +appKeywordUrl.getThemeWordsList, queryData).then((data: any) => {

      if (data.result_code == '0000') {
        node['children'] = this._toTree(data.result, node['themeWordsId'], 'themeWordsId', 'parentid', 'name');
        this.files = [...this.files];
        return false;
      } else {
        this.hintsService.messages(data.message, data.result_code);
      }

    }).catch();
  }

  _processTreeData(list: Array<any>, idName, parentIdName, labelName): Array<any> {
    return this._toTree(list, '0', idName, parentIdName, labelName);
  }

  _toTree(list: Array<any>, topId = '0', idName, parentIdName, labelName) {
    let idKey = idName;
    let result = [];
    for (let item of list) {
      if (item[parentIdName] == topId) {

        let children = {};
        let expandedIcon = 'fa fa-folder-open';
        let collapsedIcon = 'fa fa-folder';
        let leaf = false;

        if (item['child'] == '0') {
          expandedIcon = '';
          collapsedIcon = '';
          leaf = true;
        }

        let dataArr = {
          'data': {
            label: item['name'],
            data: item['themeTableId'],
            expandedIcon: expandedIcon,
            collapsedIcon: collapsedIcon,

            arrchildid: item['arrchildid'],
            arrparentid: item['arrparentid'],
            checkStatus: item['checkStatus'],
            createBy: item['createBy'],
            child: item['child'],
            name: item['name'],
            createTime: item['createTime'],
            status: item['status'],
            themeCode: item['themeCode'],
            themeGroupId: item['themeGroupId'],
            themeTableId: item['themeTableId'],
            themeWordsId: item['themeWordsId'],
            parentid: item['parentid'],
            description: item['description'],
            labelId: item['labelId'],
            labelName: item['labelName'],
          },
          'leaf': leaf,
          'themeWordsId': item['themeWordsId']
        };

        result.push(dataArr);
      }
    }
    return result;
  }


  /**
     * 全选
     * @param bool
     * @param keywordTabVal
     */
  _selectAll(bool, keywordTabVal) {
    this.isSelectAll = this.isChose = this.removeTableService.keywordRemoveAll(bool, keywordTabVal, 'themeWordsId');
    if (this.isSelectAll == false) {
      this._keyworkTabList();
    }
  }

  /**
   * 单选
   * @param bool
   * @param themeWordsId
   * @param length
   */
  _chose(bool, themeWordsId, length) {
    this.isSelectAll = this.removeTableService.keywordRemoveChose(bool, themeWordsId, length)['bool'];
  }

  /**
   * 重置表格复选框、选中的ID
   */
  private _cancelChecked() {
    this.isChose = this.isSelectAll = false;
    this.removeTableService._clearId("themeWordsId");
  }

  //查询参数
  private _tableData() {
    return {
      token: keyword.retrieval.token,
      pageNo: keyword.pagination.pageNo,
      pageSize: keyword.pagination.pageSize,
      status: keyword.retrieval.status,
      labelId: keyword.retrieval.labelId,
      themeCode: keyword.retrieval.themeCode,
      checkStatus: this.tabCheckStatus,
      startTime: keyword.retrieval.startTime,
      endTime: keyword.retrieval.endTime,
      queryCriteria: keyword.retrieval.queryCriteria,
      themeTableId: keyword.retrieval.themeTableId,
      parentId: keyword.retrieval.parentId
    }
  }

  onNodeExpand(event) {
    const node = event.node;
    let queryData = {
      token: keyword.retrieval.token,
      //checkStatus   : this.tabCheckStatus,
      themeTableId: keyword.retrieval.themeTableId,
      pageNo: 1,
      pageSize: 9999,
      parentId: node.themeWordsId
    };
    this.getChildrenList(queryData, node);
  }

  /**
  * 单条审核还是取消审核
  */
  changeCheckStatus(id: any, val: any) {
    this.changeCheck = val;
    this.removeTableService.getRemoveTableId = [];
    this.removeTableService.keywordRemoveChose(true, id, 1)['bool'];
  }

  /**
   * 单条 审核或取消审核
   */
  _review(val: any) {
    this.removeTableService
      .confirmEnableDisable(keyword.retrieval.token, 'ids', this.server.baseUrl +appKeywordUrl.updateThemeWordsCheckStatus, 'checkStatus', val)
      .then(res => {
        if (res.result_code == "0000") {
          this._keyworkTabList();
          this.removeTableService.getRemoveTableId = [];
        }
        this.hintsService.messages(res.message, res.result_code);
        return;
      })
      .catch(err => {
        this.hintsService.messages('error', 'error');
        return;
      });
  }

  /**
   * 获取主题词标签列表
   */
  _themeTagList(){
    let data = {
      token         : keyword.retrieval.token,
      pageNo        : 1,
      pageSize      : 999,
    };
    this.request.postRequest(this.server.baseUrl +appKeywordUrl.getThemeWordsLabelList,data).then((res:any) => {
      if (res.result_code === '0000') {
        this.themeTagListVal = res.result;
      }else{
        this.hintsService.messages(res.message,res.result_code);
      }
      return;
    })
    .catch((err: any)=>{
      this.hintsService.messages("error","error");
      return;
    });
  }

}
